// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#pragma once

#include <stdio.h>
#include <vector>
#include <kmsql/sql/grammar/expr.h>

namespace kmsql {

struct SelectStatement;
struct JoinDefinition;
struct TableRef;

// Possible table reference types.
enum TableRefType { kTableName, kTableSelect, kTableJoin, kTableCrossProduct };

struct TableName {
  char* schema;
  char* name;
};

struct Alias {
  Alias(char* name, std::vector<char*>* columns = nullptr);
  ~Alias();

  char* name;
  std::vector<char*>* columns;
};

// Holds reference to tables. Can be either table names or a select statement.
struct TableRef {
  TableRef(TableRefType type);
  virtual ~TableRef();

  TableRefType type;

  char* schema;
  char* name;
  Alias* alias;

  SelectStatement* select;
  std::vector<TableRef*>* list;
  JoinDefinition* join;

  // Returns true if a schema is set.
  bool hasSchema() const;

  // Returns the alias, if it is set. Otherwise the name.
  const char* getName() const;
};

// Possible types of joins.
enum JoinType { kJoinInner, kJoinFull, kJoinLeft, kJoinRight, kJoinCross, kJoinNatural };

// Definition of a join construct.
struct JoinDefinition {
  JoinDefinition();
  virtual ~JoinDefinition();

  TableRef* left;
  TableRef* right;
  Expr* condition;
  std::vector<char*>* namedColumns;

  JoinType type;
};

}  // namespace kmsql
